package org.example.nio.client;

import cn.hutool.core.thread.ThreadUtil;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class SBClient {
    public static final int  CONNECT_TIMEOUT = 3000;
    private static final String HOSTNAME = "localhost";
    private static final int PORT = 9123;

    public static void main(String[] args) throws Throwable {

        NioSocketConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);

        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory( Charset.forName( "UTF-8" ))));

        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new SBClientHandler());
        IoSession session;

        for (;;) {
            try {
                ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
                future.awaitUninterruptibly();
                session = future.getSession();
                break;
            } catch (RuntimeIoException e) {
                System.err.println("Failed to connect.");
                e.printStackTrace();
                Thread.sleep(5000);
            }
        }
        int i = 0;
        while(i < 1000){
            session.write("ping");
            ThreadUtil.safeSleep(1000);
        }

        // wait until the summation is done
//        session.getCloseFuture().awaitUninterruptibly();
//        connector.dispose();
    }
}
